import sys
import io
import argparse
from pathlib import Path
from tqdm import tqdm

def save_manifest(path_list, path_save):
    with io.FileIO(str(path_save), "w") as f:
        for item in path_list:
            f.write((item + "\n").encode('utf-8'))

def arg_parser():
    parser = argparse.ArgumentParser("Extract video frames")
    parser.add_argument("--path_frames", type=str, help="video path for extract")
    parser.add_argument("--path_manifest", type=str, default="./manifest.csv", help='save extraction frames')
    parser.add_argument("--override", action='store_true', help="if override origin frames")
    args = parser.parse_args()
    return args


if __name__ == "__main__":
    
    args = arg_parser()

    path_frames = Path(args.path_frames)
    path_manifest = Path(args.path_manifest)
    
    v_files = sorted(path_frames.glob("*"))
    n_frames = len(v_files)
    print(f"Contain {n_frames} frames, {path_frames}")

    # check other data
    path_landmk = path_frames.parent.joinpath("landmk")
    path_landmk_bbox = path_frames.parent.joinpath("landmk_bbox")
    n_landmk = len(list(path_landmk.glob("*")))
    n_landmk_bbox = len(list(path_landmk_bbox.glob("*")))
        
    if n_frames < 25 or n_landmk != n_frames or n_landmk_bbox != n_frames:
        raise(f"The frame is less than 25 or n_landmk != n_frames != n_landmk_bbox, which is {n_frames} in {path_frames}")
        
    v_frames_files = ["1"] + [str(kk) for kk in v_files]

    # save
    print(f"create manifest file -> {path_manifest}")
    save_manifest(v_frames_files, path_manifest)
